//
//  ArticlePageViewController.swift
//  
//
//  Created by Ralf on 6/12/15.
//
//

import UIKit

class ArticlePageViewController: TableViewController, UMSocialUIDelegate
{
    let appDelegate     = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen          = UIScreen.mainScreen().bounds
    var activity:          NSMutableDictionary!
    var pageViewImageCell: PageViewImageCell!
    var relatedProducts = NSMutableArray()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.registerNib(UINib(nibName: "PageViewAvatarCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AVATAR")
        self.tableView.registerNib(UINib(nibName: "PageViewImageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "IMAGE")
        self.tableView.registerNib(UINib(nibName: "PageViewMessageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MESSAGE")
        self.tableView.registerNib(UINib(nibName: "PageViewLinkCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "LINK")
        self.tableView.registerNib(UINib(nibName: "PageViewOtherProductCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "PRODUCT")

        initBackButton()
        initReportButton()
        loadRelatedProducts()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    func initReportButton()
    {
        let image  = UIImage(named: "Share-Small.png")!.imageWithRenderingMode(.AlwaysOriginal)
        let button = UIBarButtonItem(image: image, style: .Plain, target: self, action: "showMenu:")
        self.navigationItem.rightBarButtonItem = button
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 4// + advertising.count
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        switch indexPath.row
        {
        case 0: //avatar
            return 60
        case 1: //image
            return screen.size.width
        case 2: // message
            let article = activity["article"] as! NSDictionary
            let message = article["message"] as! NSString
            let size    = sizeOfText(message)
            //let size = message.boundingRectWithSize(frame, options: .DrawingTruncatesLastVisibleLine | .DrawingUsesLineFragmentOrigin | DrawingUsesFontLeading, attributes: attribute, context: nil)
            return size.height * 1.4
        case 3:
            return 30.0
        default: // related service
            return UIScreen.mainScreen().bounds.size.width / 4 + 45
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        switch indexPath.row
        {
        case 0:
            let cell = tableView.dequeueReusableCellWithIdentifier("AVATAR", forIndexPath: indexPath) as! PageViewAvatarCell
            cell.setData(activity)
            return cell
        case 1:
            //let article = activity["article"] as! NSDictionary
            pageViewImageCell = tableView.dequeueReusableCellWithIdentifier("IMAGE", forIndexPath: indexPath) as! PageViewImageCell
            pageViewImageCell.setData(activity)
            return pageViewImageCell
        case 2:
            let cell = tableView.dequeueReusableCellWithIdentifier("MESSAGE", forIndexPath: indexPath) as! PageViewMessageCell
            cell.setData(activity)
            return cell
        default:
            let cell = tableView.dequeueReusableCellWithIdentifier("LINK", forIndexPath: indexPath) as! PageViewLinkCell
            cell.setData(activity)
            return cell
        }
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()

        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 20
        paragraphStyle.minimumLineHeight = 20

        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left

        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),
                          NSParagraphStyleAttributeName: paragraphStyle,
                          NSForegroundColorAttributeName: UIColor.darkGrayColor()]

        let frame = CGSizeMake(screen.size.width, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue|NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }

    @IBAction func showMenu(sender: AnyObject)
    {
        let text         = activity.objectForKey("article")?.objectForKey("message") as! String
        let thumbnailURL = activity.objectForKey("article")?.objectForKey("thumbnailURL") as! String
        let url          = appDelegate.parameterManager.server + "/" + thumbnailURL
        let data         = NSData(contentsOfURL: NSURL(string: url)!)
        let image        = UIImage(data: data!)
        UMSocialSnsService.presentSnsIconSheetView(self, appKey: UMSocialData.appKey(), shareText: text as String, shareImage: image, shareToSnsNames: [UMShareToQzone, UMShareToWechatTimeline, UMShareToWechatSession, UMShareToWechatFavorite, UMShareToSina, UMShareToSms, UMShareToQQ, UMShareToTencent], delegate: self)
    }

    func loadRelatedProducts()
    {
        let article  = activity["article"] as! [String:AnyObject]
        let contact  = article["contact"] as! [String:AnyObject]
        let userName = contact["userName"] as! String

        let advertisingManager = AdvertisingManager()
        let rs                 = advertisingManager.queryAdvertisingByUserName(userName, max: 4, offset: 0)

        if rs != nil && !rs.hasErrors() && !rs.isEmpty()
        {
            relatedProducts.addObjectsFromArray(rs.toMutableArray() as [AnyObject])
        }
    }
}
